<template>
  <div class="staff"> 
    <PanelHead :route="route" />
  </div>
  <div class="btns">
    <el-button :icon="Plus" type="primary" @click="open" size="small">添加</el-button>
  <el-popconfirm title="是否确认删除?"
  icon-color="red"
  :icon="InfoFilled"
  confirm-button-text="删除"
  cancel-button-text="取消"
  @confirm="handleDelete"
  >
    <template #reference>
      <el-button :icon="Delete" type="danger" size="small">Delete</el-button>
    </template>
  </el-popconfirm>
  </div>
  


  <div class="companion"> 
    <el-table
      :data="companionData.list"
      style="width: 100%"
      @selection-change="handleSelectionChange"

    >
    <el-table-column type="selection" width="55" >
      </el-table-column>
    <el-table-column label="ID" prop='id' >
      </el-table-column>
      <el-table-column label="姓名" prop='name' >
      </el-table-column>
      <el-table-column label="头像" prop='avatar' >
        <template #default="scope">
          <el-image 
            :src="scope.row.avatar" 
            style="width: 50px; height: 50px;" 
            fit="cover"
            v-if="scope.row.avatar">
          </el-image>
          </template>
  </el-table-column>
      <el-table-column label="手机号" prop="mobile">
      </el-table-column>
    <el-table-column label="性别" prop="sex">
      <template #default="scope">
        {{ scope.row.sex == 1 ? '男' : '女' }}
      </template>
  </el-table-column>
  <el-table-column label="年龄" prop='age' >
      </el-table-column>
      <el-table-column label="状态" prop="active" width="80px">
        <template #default="scope">
          <el-tag :type="scope.row.active ? 'success' : 'danger'">{{scope.row.active? '正常' : '失效'}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" >
        <template #default="scope">
          <span>{{scope.row.create_time}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <!-- 修复：传递当前行数据给open函数 -->
          <el-button @click="open(scope.row)" type="primary">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加分页组件 -->
    <el-pagination
      v-model:current-page="pagination.pageNum"
      v-model:page-size="pagination.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :total="companionData.total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      class="pagination"
    />
  </div>
  <el-dialog v-model="dialogFormVisible" :before-close="beforeClose" title="陪护师添加">
    <el-form ref="formRef" :model="form" label-width="80px" :rules="rules">
      <el-form-item v-show=false prop="id">
        <el-input v-model="form.id"></el-input>
      </el-form-item>
      <el-form-item label="昵称" prop="name">
        <el-input v-model="form.name" placeholder="请输入昵称"></el-input>
      </el-form-item>
      <el-form-item label="头像" prop="avatar">
        <el-button v-if="!form.avatar" type="primary" @click="dialogImgVisible = true;">上传</el-button>
        <el-image v-else :src="form.avatar" style="width: 100px; height: 100px;"></el-image>
      </el-form-item>

      <el-form-item label="性别" prop="sex">
        <el-select v-model="form.sex" placeholder="请选择性别">
          <el-option label="男" value="1"></el-option>
          <el-option label="女" value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="年龄" prop="age">
        <el-input-number v-model="form.age" :min="18" :max="50"></el-input-number>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="form.mobile" placeholder="请输入手机号"></el-input>
      </el-form-item>
      <el-form-item label="是否生效" prop="active">
        <el-radio-group v-model="form.active">
          <el-radio :value="1">生效</el-radio>
          <el-radio :value="0">失效</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog v-model="dialogImgVisible" 
  :before-close="beforeClose" 
  title="上传头像" 
  width="600px"
  >
    <div class="image-list">
      <div v-for="(item, index) in fileList" :key="item.name" class="img-box" @click="selectIndex = index;console.log(item.url)">
        <div v-if="selectIndex === index" class="select">
          <el-icon color="#fff">
            <Check />
          </el-icon>
        </div>
        <el-image :src="item.url" fit="cover" style="width: 148px; height: 148px;"></el-image>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogImgVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmImage">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { reactive, ref, onMounted,nextTick} from 'vue'
import { Plus,Check, InfoFilled,Delete } from '@element-plus/icons-vue'
import { photoList,companion,companionList,companionDelete } from '../../api'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs';
import { useRoute } from 'vue-router';
import PanelHead from '../../components/panelHead.vue';
import { id } from 'element-plus/es/locales.mjs';

const route = useRoute()

const companionData = reactive({
  list: [],
  total: 0
})


const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
});

// 处理分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  getListData()
};

// 处理当前页变化
const handleCurrentChange = (val) => {
  pagination.pageNum = val
  getListData()
};

onMounted(() => {
  photoList().then((res) => {
    // console.log(res.data)
    fileList.value = res.data.data
  })
  getCompanionList()
})


const confirmImage = () => { 
  form.avatar = fileList.value[selectIndex.value].url
  console.log(fileList.value,'fileList.value,,,confirm')
  dialogImgVisible.value = false
}

const dialogFormVisible = ref(false)
const beforeClose = () => {
  dialogFormVisible.value = false
  formRef.value.resetFields()
}

const formRef = ref()
const form = reactive({
  id: '',
  mobile: '',
  active: 1,
  age: 21,
  avatar: '',
  name: '',
  sex: '',
})

const rules = reactive({
  name: [
    { required: true, 
      message: '请输入昵称', 
      trigger: 'blur' },
  ],
  avatar: [
    { required: true, 
      message: '请上传头像', 
      trigger: 'blur' },
  ],
  sex: [
    { required: true, 
      message: '请选择性别', 
      trigger: 'blur' },
  ],
  mobile: [
    { required: true, 
      message: '请输入手机号', 
      trigger: 'blur' },
  ],
})

const getCompanionList = () => { 
  companionList(paginationData).then(res => { 
    console.log(res.data.data, '获取的 companionList')
    const {list , total} = res.data.data
    list.forEach(element => {
      element.create_time = dayjs(element.create_time).format('YYYY-MM-DD')
    });
    companionData.list = list
    companionData.total = total
  })  
}

const paginationData = reactive({
  pageNum: 1,
  pageSize: 10,
});



const confirm = async () => {
  await formRef.value.validate((valid) => {
    if (!valid) return
    if (valid) {
      companion(form).then(({data}) => { 
        console.log(data);
        if(data.code === 10000){
          ElMessage.success('添加成功')
          beforeClose()
          getCompanionList()

        }else{ 
          ElMessage.error(data.message)
        }
})
    } else {

    }
  })
}


const dialogImgVisible = ref(false)
const fileList = ref([])
const selectIndex = ref(0)

const selectTableData = ref([])

const handleSelectionChange = (val) => { 
  selectTableData.value = val
}

const open = (rowData) => {
  dialogFormVisible.value = true
  nextTick(() => { 
    if(rowData){ 
      Object.assign(form, rowData)
    }
  })
}


const handleDelete = () => {
  if(!selectTableData.value.length){
    return ElMessage.warning('请选择要删除的行')
  }
  companionDelete({id:selectTableData.value}).then(({data}) => { 
        if(data.code === 10000){ 
        getCompanionList()
        return ElMessage.success('删除成功')
        
      }
  })
}

  



</script>

<style scoped>
.btns {
  padding: 10px 0 10px 10px;
  background-color: #fff;
}

.image-list {
  display: flex;
  align-items: center;
  flex-wrap: wrap;

  .img-box {
    position: relative;

    .select {
      position: absolute;
      left: 0px;
      top: 0px;
      width: 24px;
      height: 24px;
      background-color: #67c23a;
      z-index: 999;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }

  .el-image {
    margin-right: 10px;
    margin-bottom: 10px;
  }
}
</style>
